package com.bai.Utils;

import com.bai.Constant.FileUploadConst;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class MyFileUtil {
    //存储文件 只有两种情况返回值为1、null路径不存在；2、返回正确的最终存储路径
    public static synchronized String  saveFile(String path, MultipartFile file) throws IOException {
        StringBuilder finalPath=new StringBuilder(path);
        if (checkPath(path)){
            finalPath.append(File.separator);
            finalPath.append(UUID.randomUUID());
            finalPath.append(file.getOriginalFilename());
            file.transferTo(new File(finalPath.toString()));
            return finalPath.toString();
        }
        return null;
    }
    //创建文件夹
    public static synchronized boolean makeFolder(String path,String name){
        if (checkPath(path)){
            return new File(path +File.separator+name).mkdir();
        }
        return false;
    }
    //删除文件
    public static synchronized boolean delFile(String path,HttpServletRequest request){
        if (checkPath(path)){
            new File(path).delete();
            return true;
        }
        return false;
    }
    //判断路径是否存在，没有就创建路径，有就跳过
    private static boolean checkPath(String path){
        boolean flag=false;
        File file=new File(path);
        if (!file.exists()){
            return false;
        }
        return true;
    }
}
